/*
 * Tiled QML plugin
 * Copyright (C) 2010 Thorbjørn Lindeijer
 * Copyright (C) 2010 Nokia Corporation
 *
 * This file is part of the Tiled QML plugin.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "mapitem.h"

#include "tilelayeritem.h"

#include "tiled/isometricrenderer.h"
#include "tiled/map.h"
#include "tiled/orthogonalrenderer.h"
#include "tiled/tilelayer.h"
#include "tiled/tmxmapreader.h"
#include "tiled/objectgroup.h"

#include "tiled/mapobject.h"

#include <QVariantList>
#include <QVariantMap>

using namespace Tiled;
using namespace Tiled::Internal;

MapItem::MapItem(QDeclarativeItem *parent)
    : QDeclarativeItem(parent)
    , mMap(0)
    , mRenderer(0)
{
    setFlags(ItemHasNoContents);
}

void MapItem::setSource(const QString &source)
{
    if (mSource == source)
        return;

    mSource = source;

    qDeleteAll(childItems());
    delete mMap;
    delete mRenderer;
    mRenderer = 0;

    Tiled::Internal::TmxMapReader reader;
    mMap = reader.read(mSource);
    if (!mMap) {
        qDebug() << "Failed to load map:" << source << "\n"
                << reader.errorString();
        return;
    }

    switch (mMap->orientation()) {
    case Map::Isometric:
        mRenderer = new IsometricRenderer(mMap);
        break;
    default:
        mRenderer = new OrthogonalRenderer(mMap);
        break;
    }

    int layerIndex = 0;
    foreach (Layer *layer, mMap->layers()) {
        if (TileLayer *tl = dynamic_cast<TileLayer*>(layer)) {
            QGraphicsItem *layerItem = new TileLayerItem(tl, mRenderer, this);
            layerItem->setZValue(layerIndex);
            ++layerIndex;
        }
    }

    const QSize size = mRenderer->mapSize();
    setImplicitWidth(size.width());
    setImplicitHeight(size.height());

    emit sourceChanged(mSource);
}

QVariantList MapItem::readGameObjects()
{
    QVariantList list;

    //look for objects layer
    ObjectGroup *objectLayer = NULL;

    foreach (Layer *layer, mMap->layers())
    {
        if (ObjectGroup *og = dynamic_cast<ObjectGroup *>(layer))
        {
            if (og->name().compare("objects", Qt::CaseInsensitive) == 0)
                objectLayer = og;
        }
    }

    if (objectLayer == NULL) return list;

    //populate list to javascript
    foreach(MapObject *obj, objectLayer->objects())
    {
        QVariantMap item;
        item.insert("x", obj->x() * mMap->tileWidth());
        item.insert("y", obj->y() * mMap->tileWidth());
        item.insert("type", obj->type());

        list << item;
    }

    return list;
}

QVariantList MapItem::readCollisionObjects()
{
    QVariantList list;

    //look for collision layer
    ObjectGroup *collisionLayer = NULL;

    foreach (Layer *layer, mMap->layers())
    {
        if (ObjectGroup *og = dynamic_cast<ObjectGroup *>(layer))
        {
            if (og->name().compare("collision", Qt::CaseInsensitive) == 0)
                collisionLayer = og;
        }
    }

    if (collisionLayer == NULL) return list;

    //populate list to javascript
    foreach(MapObject *obj, collisionLayer->objects())
    {
        QVariantMap item;
        item.insert("x", obj->x() * mMap->tileWidth());
        item.insert("y", obj->y() * mMap->tileWidth());

        if (obj->shape() == MapObject::Polygon)
        {
            QVariantList pointsList;
            QVariantMap pointItem;

            foreach (QPointF point, obj->polygon())
            {
                pointItem.clear();
                pointItem.insert("x", point.x() * mMap->tileWidth());
                pointItem.insert("y", point.y() * mMap->tileHeight());

                pointsList << pointItem;
            }

            item.insert("vertices", pointsList);
            item.insert("shape", "polygon");
        }
        else // Rectangle
        {
            item.insert("height", obj->height() * mMap->tileHeight());
            item.insert("width", obj->width() * mMap->tileWidth());
            item.insert("shape", "rectangle");
        }

        list << item;
    }

    return list;
}

QRectF MapItem::boundingRect() const
{
    if (!mMap)
        return QRectF();

    return QRectF(QPointF(), mRenderer->mapSize());
}
